#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

SL* BuySList(SLDatatype n)
{
	SL*ptr = (SL*)malloc(sizeof(SL));
	if (ptr==NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	ptr->next = NULL;
	ptr->x = n;
	return ptr;
}

SL* CreateSL(int x)
{
	assert(0!=x);
	SL*ps = BuySList(0);
	SL* ptr = ps;
	for (int i = 1; i < x; i++)
	{
			ps->next= BuySList(i);
			ps = ps->next;
	}
	return ptr;
}

void PrintSL(SL*ps)
{
	while (ps)
	{
		printf("%d->", ps->x);
		ps = ps->next;
	}
	printf("NULL\n");
}

 void SLPushback(SL**pps,SLDatatype x)
{
	 if (*pps==NULL)
	 {
		 *pps = BuySList(x);
	 }
	 else
	 {
		 SL*phead = *pps;
		 while ((*pps)->next)
		 {
			 *pps = (*pps)->next;
		 }
		 (*pps)->next = BuySList(x);
		 *pps = phead;
	 }
}

 void SLPopback(SL**pps)
 {
	 assert(*pps);
	 if ((*pps)->next==NULL)
	 {
		 free(*pps);
		 *pps = NULL;
	 }
	 else
	 {
		 SL*phead = *pps;
		 while ((*pps)->next->next)
		 {
			 *pps = (*pps)->next;
		 }
		 free((*pps)->next);
		 (*pps)->next = NULL;
		 *pps = phead;
	 }
 }

 void SLPushFront(SL**pps, SLDatatype x)
 {
	 if (*pps==NULL)
	 {
		 *pps = BuySList(x);
	 }
	 else
	 {
		 SL*ptr = *pps;
		 *pps = BuySList(x);
		 (*pps)->next = ptr;
	 }
 }

 void SLPopFront(SL**pps)
 {
	 assert(*pps);
		 SL*ptr = (*pps)->next;
		 free(*pps);
		 *pps = ptr;
 }
 SL*SLFind(SL*ps,int pos)
 {
	 if (ps==NULL)
	 {
		 return NULL;
	 }
	 while (ps->x!=pos)
	 {
		
		 if (ps->next!=NULL)
		 {
			 ps = ps->next;
		 }
		 else
		 {
			 return ps;
		 }
	 }
	 return ps;
 }

 void SLinsertAfter(SL*ps, int pos, SLDatatype x)
 {
	 SL*cur = SLFind(ps, pos);
	 SL*ptr = BuySList(x);
	 if (cur==NULL)
	 {
		 return ptr;
	 }
	 ptr->next = cur->next;
	 cur->next = ptr;
 }

 void SLinsert(SL**pps, int pos, SLDatatype x)
 {
	 SL*cur = SLFind(*pps, pos);
	 SL*ptr = BuySList(x);
	 SL*src = NULL;
	 SL*ps = *pps;
	 assert(cur->next != NULL);
	 if (cur == NULL)
	 {
		 return ptr;
	 }
	 
	 while (ps->next!=cur)
	 {
		 src = ps;
		 ps = ps->next;
	 }
	 if (ps==*pps)
	 {
		 ptr->next = ps;
		 *pps = ptr;
	 }
	 else
	 {
		 ptr->next = src->next;
		 src->next = ptr;
	 }
	
 }